<template>
  <div class="agent-create-page">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button @click="$router.go(-1)" text>
            <i class="el-icon-arrow-left"></i>
            返回
          </el-button>
          <h1>创建智能体</h1>
        </div>
      </div>
    </div>

    <div class="page-content">
      <el-card class="create-form-card">
        <el-form
          ref="agentFormRef"
          :model="agentForm"
          :rules="rules"
          label-width="120px"
          size="large"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            
            <el-form-item label="智能体名称" prop="name" required>
              <el-input
                v-model="agentForm.name"
                placeholder="为您的智能体起一个名字"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="智能体类型" prop="agent_type" required>
              <el-select v-model="agentForm.agent_type" placeholder="选择智能体类型" style="width: 100%;">
                <el-option
                  v-for="type in agentTypes"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
                >
                  <div class="type-option">
                    <strong>{{ type.name }}</strong>
                    <small>{{ type.description }}</small>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="描述" prop="description" required>
              <el-input
                v-model="agentForm.description"
                type="textarea"
                :rows="3"
                placeholder="描述您的智能体的功能和特点"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="头像">
              <el-input
                v-model="agentForm.avatar"
                placeholder="头像图片URL（可选）"
              />
            </el-form-item>
          </div>

          <!-- AI配置 -->
          <div class="form-section">
            <h3 class="section-title">AI配置</h3>
            
            <el-form-item label="系统提示词" prop="system_prompt" required>
              <el-input
                v-model="agentForm.system_prompt"
                type="textarea"
                :rows="5"
                placeholder="定义智能体的角色、行为和回答风格..."
                maxlength="2000"
                show-word-limit
              />
              <div class="form-hint">
                系统提示词将决定智能体的性格和行为模式，请详细描述您希望智能体如何与用户交互。
              </div>
            </el-form-item>

            <el-form-item label="AI模型">
              <el-select v-model="agentForm.model_name" placeholder="选择AI模型">
                <el-option label="GPT-3.5 Turbo" value="gpt-3.5-turbo" />
                <el-option label="GPT-4" value="gpt-4" />
                <el-option label="GPT-4 Turbo" value="gpt-4-turbo-preview" />
              </el-select>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="创造性">
                  <el-slider
                    v-model="agentForm.temperature"
                    :min="0"
                    :max="2"
                    :step="0.1"
                    show-tooltip
                  />
                  <div class="form-hint">
                    较低值(0.1-0.5)使回答更加专注和确定，较高值(0.8-1.5)使回答更有创意
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大令牌数">
                  <el-input-number
                    v-model="agentForm.max_tokens"
                    :min="100"
                    :max="4000"
                    :step="100"
                    style="width: 100%;"
                  />
                  <div class="form-hint">
                    控制回答的最大长度
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 个性设置 -->
          <div class="form-section">
            <h3 class="section-title">个性设置</h3>
            
            <el-form-item label="知识领域">
              <el-select
                v-model="agentForm.knowledge_domains"
                multiple
                filterable
                allow-create
                placeholder="选择或输入知识领域标签"
                style="width: 100%;"
              >
                <el-option
                  v-for="domain in knowledgeDomains"
                  :key="domain"
                  :label="domain"
                  :value="domain"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="能力标签">
              <el-select
                v-model="agentForm.capabilities"
                multiple
                filterable
                allow-create
                placeholder="选择或输入能力标签"
                style="width: 100%;"
              >
                <el-option
                  v-for="capability in capabilities"
                  :key="capability"
                  :label="capability"
                  :value="capability"
                />
              </el-select>
            </el-form-item>
          </div>

          <!-- 发布设置 -->
          <div class="form-section">
            <h3 class="section-title">发布设置</h3>
            
            <el-form-item label="可见性">
              <el-radio-group v-model="agentForm.is_public">
                <el-radio :label="false">私有 - 仅我可见</el-radio>
                <el-radio :label="true">公开 - 所有人可见</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button @click="$router.go(-1)">取消</el-button>
            <el-button @click="saveDraft" :loading="saving">保存草稿</el-button>
            <el-button type="primary" @click="createAgent" :loading="creating">
              创建智能体
            </el-button>
          </div>
        </el-form>
      </el-card>

      <!-- 预设模板 -->
      <el-card class="templates-card">
        <template #header>
          <h3>快速开始模板</h3>
        </template>
        <div class="templates-grid">
          <div
            v-for="template in templates"
            :key="template.id"
            class="template-card"
            @click="applyTemplate(template)"
          >
            <div class="template-icon">
              <i :class="template.icon"></i>
            </div>
            <h4>{{ template.name }}</h4>
            <p>{{ template.description }}</p>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { agentApi } from '@/services/api'
import { useAppStore } from '@/stores/app'

const router = useRouter()
const appStore = useAppStore()

const agentFormRef = ref()
const creating = ref(false)
const saving = ref(false)
const agentTypes = ref([])

const agentForm = reactive({
  name: '',
  description: '',
  avatar: '',
  agent_type: '',
  system_prompt: '',
  model_name: 'gpt-3.5-turbo',
  temperature: 0.7,
  max_tokens: 2048,
  knowledge_domains: [],
  capabilities: [],
  is_public: false
})

const rules = {
  name: [
    { required: true, message: '请输入智能体名称', trigger: 'blur' },
    { min: 2, max: 100, message: '名称长度为2-100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入智能体描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度为10-500个字符', trigger: 'blur' }
  ],
  agent_type: [
    { required: true, message: '请选择智能体类型', trigger: 'change' }
  ],
  system_prompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' },
    { min: 20, max: 2000, message: '系统提示词长度为20-2000个字符', trigger: 'blur' }
  ]
}

const knowledgeDomains = [
  '编程开发', '数据科学', '人工智能', '机器学习', '深度学习',
  '前端开发', '后端开发', '移动开发', '游戏开发', '算法',
  '数学', '物理', '化学', '生物', '历史', '文学', '语言学习',
  '商业分析', '市场营销', '项目管理', '设计', '艺术'
]

const capabilities = [
  '代码编写', '代码审查', '算法设计', '系统架构', '调试排错',
  '技术咨询', '学习指导', '知识问答', '文档编写', '项目规划',
  '创意思考', '问题分析', '数据分析', '报告生成', '翻译'
]

const templates = [
  {
    id: 1,
    name: '编程导师',
    icon: 'el-icon-cpu',
    description: '专业的编程学习和代码指导助手',
    template: {
      agent_type: 2,
      system_prompt: '你是一位经验丰富的编程导师，擅长多种编程语言和技术栈。你的任务是帮助学习者理解编程概念，解决代码问题，提供最佳实践建议。请用友善、耐心的方式回答问题，并在适当时候提供代码示例。',
      knowledge_domains: ['编程开发', '算法', '数据结构'],
      capabilities: ['代码编写', '代码审查', '算法设计', '技术咨询']
    }
  },
  {
    id: 2,
    name: '学习助手',
    icon: 'el-icon-medal',
    description: '帮助学生学习各种学科知识的AI助手',
    template: {
      agent_type: 1,
      system_prompt: '你是一位专业的学习助手，善于解释复杂概念，制定学习计划，并提供个性化的学习建议。你能够适应不同学习者的水平，用简单易懂的方式解释知识点。',
      knowledge_domains: ['数学', '物理', '化学', '生物'],
      capabilities: ['知识问答', '学习指导', '问题分析']
    }
  },
  {
    id: 3,
    name: '语言伙伴',
    icon: 'el-icon-chat-line-round',
    description: '帮助用户学习和练习外语的对话伙伴',
    template: {
      agent_type: 3,
      system_prompt: '你是一位友善的语言学习伙伴，能够帮助用户练习口语、纠正语法错误、扩展词汇量。请根据用户的语言水平调整你的回答复杂度，并在对话中适时提供语言学习建议。',
      knowledge_domains: ['语言学习', '文学'],
      capabilities: ['语法纠错', '词汇扩展', '口语练习']
    }
  }
]

onMounted(() => {
  loadAgentTypes()
})

const loadAgentTypes = async () => {
  try {
    const response = await agentApi.getAgentTypes()
    agentTypes.value = response.data
  } catch (error) {
    console.error('Failed to load agent types:', error)
    appStore.showError('加载智能体类型失败')
  }
}

const applyTemplate = (template) => {
  Object.assign(agentForm, template.template)
  appStore.showSuccess(`已应用 ${template.name} 模板`)
}

const createAgent = async () => {
  if (!agentFormRef.value) return
  
  try {
    const valid = await agentFormRef.value.validate()
    if (!valid) return
    
    creating.value = true
    const response = await agentApi.createAgent({
      ...agentForm,
      status: 'active'
    })
    
    appStore.showSuccess('智能体创建成功！')
    router.push(`/agents/${response.data.id}`)
  } catch (error) {
    console.error('Failed to create agent:', error)
    appStore.showError('创建智能体失败')
  } finally {
    creating.value = false
  }
}

const saveDraft = async () => {
  if (!agentFormRef.value) return
  
  try {
    const valid = await agentFormRef.value.validate()
    if (!valid) return
    
    saving.value = true
    const response = await agentApi.createAgent({
      ...agentForm,
      status: 'draft'
    })
    
    appStore.showSuccess('草稿保存成功！')
    router.push(`/agents/${response.data.id}`)
  } catch (error) {
    console.error('Failed to save draft:', error)
    appStore.showError('保存草稿失败')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped lang="scss">
.agent-create-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
  display: flex;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  
  h1 {
    margin: 0;
    font-size: 1.5rem;
    color: var(--el-text-color-primary);
  }
}

.page-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.create-form-card {
  :deep(.el-card__body) {
    padding: 30px;
  }
}

.form-section {
  margin-bottom: 32px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid var(--el-color-primary);
  font-size: 1.25rem;
  color: var(--el-text-color-primary);
}

.form-hint {
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  line-height: 1.4;
}

.type-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  
  strong {
    font-size: 14px;
  }
  
  small {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.templates-card {
  :deep(.el-card__header) {
    padding: 20px 20px 0;
  }
  
  :deep(.el-card__body) {
    padding: 20px;
  }
  
  h3 {
    margin: 0;
    font-size: 1.125rem;
    color: var(--el-text-color-primary);
  }
}

.templates-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.template-card {
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
  }
}

.template-icon {
  width: 40px;
  height: 40px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  
  i {
    font-size: 20px;
  }
}

.template-card h4 {
  margin: 0 0 8px 0;
  font-size: 1rem;
  color: var(--el-text-color-primary);
}

.template-card p {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
}

@media (max-width: 992px) {
  .page-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>